package com.ovopark.websocket

import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft
import org.java_websocket.drafts.Draft_6455
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.net.URISyntaxException

/**
 * Java_WebSocket
 * Created by cz on 2016/5/10.
 */
class JavaWebSocket(
    serverUri: URI?,
    protocolDraft: Draft?,
    httpHeaders: Map<String?, String?>?,
    connectTimeout: Int
) : WebSocketClient(serverUri, protocolDraft, httpHeaders, connectTimeout) {
    interface OnGetWebSocketCallback {
        fun onOpen(serverHandshake: ServerHandshake?)
        fun onMessage(s: String?)
        fun onClose(i: Int, s: String?, b: Boolean)
        fun onError(e: Exception?)
    }

    private var callback: OnGetWebSocketCallback? = null
    override fun onOpen(serverHandshake: ServerHandshake) {
        if (callback != null) {
            callback!!.onOpen(serverHandshake)
        }
    }

    override fun onMessage(s: String) {
        if (callback != null) {
            callback!!.onMessage(s)
        }
    }

    override fun onClose(i: Int, s: String, b: Boolean) {
        if (callback != null) {
            callback!!.onClose(i, s, b)
        }
    }

    override fun onError(e: Exception) {
        if (callback != null) {
            callback!!.onError(e)
        }
    }

    companion object {
        @JvmStatic
        fun getInstance(
            url: String?,
            httpHeaders: Map<String?, String?>?,
            callback: OnGetWebSocketCallback?
        ): JavaWebSocket {
            var serverUri: URI? = null
            try {
                serverUri = URI(url)
            } catch (e: URISyntaxException) {
                e.printStackTrace()
            }
            val javaWebSocket = JavaWebSocket(serverUri, Draft_6455(), httpHeaders, 30 * 1000)
            javaWebSocket.callback = callback
            return javaWebSocket
        }
    }
}